<template>
  <div class="w-full flex flex-col flex-wrap gap-2">
    <div v-for="(item, index) in dataRef" :key="index" class="flex gap-2 items-center">
      <Select
        :options="filedList"
        v-model:value="item.calcFieldCode"
        style="width: 150px"
        show-search
        optionFilterProp="label"
        @change="handleChange"
        :getPopupContainer="(trigger) => trigger?.parentNode"
      />
      <Select
        :options="calcFuncList"
        v-model:value="item.calcFunc"
        style="width: 100px"
        @change="handleChange"
        :getPopupContainer="(trigger) => trigger?.parentNode"
      />
      <span class="cursor-pointer" @click="handleDelete(index)">x</span>
    </div>
  </div>
</template>
<script lang="ts" setup>
  import { ref, watch, unref, onMounted } from 'vue';
  import { Select } from 'ant-design-vue';
  import { isArray } from '/@/utils/is';
  import { getFormGetFieldsByNumeric } from '/@/api/formDesign/formDesign';
  const emit = defineEmits(['update:modelValue']);
  const props = defineProps({
    modelValue: {
      type: Object as PropType<object>,
      default: () => {
        return {};
      },
    },
    formCode: {
      type: String,
      default: '',
    },
  });
  const dataRef = ref<Recordable[]>([]);
  const filedList = ref<Recordable[]>([]);

  const calcFuncList = [
    {
      value: '0',
      label: '求和',
    },
    {
      value: '1',
      label: '求平均值',
    },
  ];

  const handleCreate = () => {
    dataRef.value.push({
      calcFieldCode: '',
      calcFunc: '0',
    });
    handleChange();
  };

  watch(
    () => props.modelValue,
    (newVal) => {
      dataRef.value = [];
      if (newVal && Object.keys(newVal).length) {
        for (let v in newVal) {
          dataRef.value.push({
            calcFieldCode: v,
            calcFunc: newVal[v],
          });
        }
      }
    },
    {
      immediate: true,
    },
  );

  const fetch = async () => {
    if (!props?.formCode) return;
    const data = await getFormGetFieldsByNumeric({ formCode: props.formCode });
    filedList.value = data;
    if (isArray(filedList.value)) {
      filedList.value.forEach((item) => {
        delete item.options;
        item.label = item.title;
        item.value = item.name;
      });
    } else {
      filedList.value = [];
    }
    filedList.value.unshift({
      value: '',
      label: '无',
    });
  };
  watch(
    () => props.formCode,
    () => {
      fetch();
    },
  );
  onMounted(fetch);

  const handleDelete = (index) => {
    dataRef.value.splice(index, 1);
    handleChange();
  };

  const handleChange = () => {
    console.log('uui', dataRef.value);
    let params = {};
    if (dataRef.value && dataRef.value.length) {
      dataRef.value.forEach((item) => {
        params[item.calcFieldCode] = item.calcFunc;
      });
    }
    emit('update:modelValue', params);
  };

  defineExpose({
    handleCreate,
  });
</script>
